package cn.laoma.thread5.t5_003_Concurrent_Container;

import lombok.SneakyThrows;
import lombok.ToString;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @program: ThreadDemos
 * @description: 是一个延时阻塞队列
 * 1.可以实现按照时间进行排序并且延迟执行的队列
 * 2.不能将null元素放置到这种队列中
 * 3.底层采用PriorityQueue来实现
 * @author: 老马
 * @create: 2021-10-03 13:36
 **/
public class T07_DelayQueue {
    static BlockingQueue<MyTask> tasks = new DelayQueue<>();
    @ToString
    static class MyTask implements Delayed{
        String name;
        long delayTime;

        public MyTask(String name, long delayTime) {
            this.name = name;
            this.delayTime = delayTime;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(delayTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            if(this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)){
                return -1;
            }else if(this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)){
                return 1;
            }
            return 0;
        }
    }

    @SneakyThrows
    public static void main(String[] args) {
        long now = System.currentTimeMillis();
        MyTask task1 = new MyTask("t1", now + 1000);
        MyTask task2 = new MyTask("t2", now + 2500);
        MyTask task3 = new MyTask("t3", now + 500);
        MyTask task4 = new MyTask("t4", now + 10000);

        tasks.put(task1);
        tasks.put(task2);
        tasks.put(task3);
        tasks.put(task4);

        //打印任务
        for (int i = 0; i < 4; i++) {
            System.out.println(tasks.take());
        }

    }


}